package com.atguigu.day07;

import com.atguigu.utils.ClickEvent;
import com.atguigu.utils.ClickSource;
import com.atguigu.utils.UrlViewCountPerWindow;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

public class Example6 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new ClickSource())
                .keyBy(r -> r.url)
                .process(new KeyedProcessFunction<String, ClickEvent, UrlViewCountPerWindow>() {
                    private long SlidingWindowSize = 10 * 1000L;
                    private long SlidingWindowStep = 5 * 1000L;

                    private MapState<Long, List<ClickEvent>> mapState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        super.open(parameters);
                        mapState = getRuntimeContext().getMapState(
                                new MapStateDescriptor<Long, List<ClickEvent>>(
                                        "mapstate",
                                        Types.LONG,
                                        Types.LIST(Types.POJO(ClickEvent.class))
                                )
                        );
                    }

                    @Override
                    public void processElement(ClickEvent value, Context ctx, Collector<UrlViewCountPerWindow> out) throws Exception {
                        // 7秒的事件
                        long currTime = ctx.timerService().currentProcessingTime();
                        ArrayList<Long> arr = new ArrayList<>();
                        long windowStartTime = getWindowStart(currTime, SlidingWindowStep);
                        for (long start = windowStartTime; start > currTime - SlidingWindowSize; start -= SlidingWindowStep) {
                            arr.add(start);
                        }

                        // 对于7秒到达的事件，arr是[5,0]
                        for (Long startTime : arr) {
                            if (!mapState.contains(startTime)) {
                                List<ClickEvent> events = new ArrayList<>();
                                events.add(value);
                                mapState.put(startTime, events);
                            } else {
                                mapState.get(startTime).add(value);
                            }

                            ctx.timerService().registerProcessingTimeTimer(startTime + SlidingWindowSize - 1L);
                        }
                    }

                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<UrlViewCountPerWindow> out) throws Exception {
                        // 用来触发窗口的计算并销毁窗口
                        // 计算出窗口结束时间
                        long windowEndTime = timestamp + 1L;
                        long windowStartTime = windowEndTime - SlidingWindowSize;
                        String url = ctx.getCurrentKey();
                        // 获取窗口中所有数据的总数
                        long count = mapState.get(windowStartTime).size();
                        // 向下游发送数据
                        out.collect(new UrlViewCountPerWindow(
                                url,
                                count,
                                windowStartTime,
                                windowEndTime
                        ));
                        // 销毁窗口
                        // .remove只清楚windowStartTime对应的键值对
                        // .clear将整个mapState清空
                        mapState.remove(windowStartTime);
                    }
                })
                .print();

        env.execute();
    }

    public static long getWindowStart(long timestamp, long slide) {
        return timestamp - (timestamp + slide) % slide;
    }
}
